<?php

namespace common\data;

use yii\data\ActiveDataProvider as BaseDataProvider;
use yii\db\QueryInterface;
use yii\base\InvalidConfigException;

/**
 * ActiveDataProvider implements a data provider based on [[\yii\db\Query]] and [[\yii\db\ActiveQuery]].
 *
 * ```php
 * $query = new Query();
 * $provider = new ActiveDataProvider([
 *     'query' => $query->from('post'),
 *     'pagination' => [
 *         'pageSize' => 20,
 *     ],
 * ]);
 *
 * // get the posts in the current page
 * $posts = $provider->getModels();
 * ```
 *
 * For more details and usage information on ActiveDataProvider, see the [guide article on data providers](guide:output-data-providers).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveDataProvider extends BaseDataProvider {

    /**
     * {@inheritdoc}
     */
    protected function prepareModels() {
        if (!$this->query instanceof QueryInterface) {
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
        }
        $query = clone $this->query;
        $sort = $this->getSort();
        if ($sort !== false) {
            $query->addOrderBy($sort->getOrders());
        }

        $pagination = $this->getPagination();
        if ($pagination !== false) {
            $pagination->totalCount = $this->getTotalCount();
            if ($pagination->totalCount === 0) {
                return [];
            }
            $query->limit($pagination->getLimit())->offset($pagination->getOffset());
        } else {
            return $query->each(100, $this->db);
        }
        return $query->all($this->db);
    }

}
